package com.fingard.dsp.bank.helpers.dbhelpers;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;


public class InsertHelper {

	/**将对象写入数据库
	 * @throws Exception */
	public static int insertObject(Connection pConn, String pTabName, Object pObj) throws Exception{
		Field[] fields = pObj.getClass().getFields();
		StringBuilder sbSql = new StringBuilder();
		ArrayList<Object> objs = new ArrayList<Object>();
		sbSql.append("insert into "+pTabName+" (");
		for(int i=0;i<fields.length;i++){
			String eachType = fields[i].getGenericType().toString().toLowerCase();
			if(objs.size() > 0){
				sbSql.append(",");
			}
			sbSql.append(fields[i].getName().toUpperCase());
			Object val = fields[i].get(pObj);
			if(eachType.contains("date") && val!=null){
				objs.add(new SimpleDateFormat(Format.DateIsoFormatStr).format(val));
			}else{
				objs.add(fields[i].get(pObj));
			}
		}
		sbSql.append(") values(");
		for(int i=0;i<objs.size();i++){
			if(i>0){
				sbSql.append(",");
			}
			sbSql.append("?");
		}
		sbSql.append(")");
		
		int rowAff = JDBCHelper.update(pConn,sbSql.toString(), objs.toArray());
        if(rowAff != 1){
        	throw new Exception("写入"+pTabName+"的影响行数："+rowAff);
        }
        return rowAff;
	}
}
